package org.budo.dubbo.protocol.http.dispatcher.servlet;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.budo.support.lang.util.ReflectUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author lmw
 */
public class DispatcherServletUtil {
    public static final boolean HAS_BUDO_SUPPORT_MVCS = ReflectUtil.hasClass("org.budo.support.mvcs.Mvcs");

    static void beforeService(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        ServletRequestAttributes attributes = new ServletRequestAttributes(httpRequest);
        RequestContextHolder.setRequestAttributes(attributes);

        if (HAS_BUDO_SUPPORT_MVCS) {
            org.budo.support.mvcs.Mvcs.setThreadLocal(servletRequest, servletResponse);
        }
    }

    public static void afterService(ServletRequest servletRequest, ServletResponse servletResponse) {
        if (HAS_BUDO_SUPPORT_MVCS) {
            org.budo.support.mvcs.Mvcs.removeThreadLocal();
        }
    }
}